<template>
  <div class="activity-container">
    <!-- 统一用户信息头部组件 -->
    <UserInfoBar />
    <div class="opening-header">
      <div class="title brush-title">活动中心</div>
    </div>
    
    <!-- 活动导航 -->
    <div class="activity-nav">
      <div 
        v-for="(tab, index) in activityTabs" 
        :key="index"
        class="nav-item"
        :class="{ 'active': currentTab === tab.id }"
        @click="tab.id === 'daily' ? switchTab('daily') : goToSubPage(tab.id)"
      >
        <div class="nav-icon">{{ tab.icon }}</div>
        <div class="nav-label">{{ tab.name }}</div>
        <div class="nav-badge" v-if="tab.hasBadge">!</div>
      </div>
    </div>
    
    <!-- 每日活跃度面板 -->
    <div v-if="currentTab === 'daily'" class="panel-container">
      <div class="activity-progress">
        <div class="progress-title">
          <span>今日活跃度: {{ taskInfo.day_score || 0 }}/{{ dailyMaxActivity }}</span>
          <span>本周活跃度: {{ taskInfo.week_score || 0 }}/{{ weeklyMaxActivity }}</span>
        </div>
        
        <!-- 每日活跃度进度条 -->
        <div class="progress-bar-container">
          <div class="progress-bar">
            <div class="progress-fill" :style="{ width: dailyProgressWidth + '%' }"></div>
          </div>
          
          <!-- 每日宝箱 -->
          <div class="box-container">
            <div 
              v-for="(box, index) in taskInfo.day_score_task || []" 
              :key="'daily-' + index"
              class="activity-box"
              :class="{ 
                'can-claim': box.status === 1, 
                'claimed': box.status === 2,
                'locked': box.status === 0
              }"
              @click="claimBox(1, box)"
              @mouseenter="showRewardTooltip($event, box, 'daily')"
              @mouseleave="hideRewardTooltip"
            >
              <div class="box-icon">{{ box.need_score }}</div>
              <div class="box-label">{{ box.status === 2 ? '已领取' : (box.status === 1 ? '可领取' : '未达成') }}</div>
            </div>
          </div>
        </div>
        
        <!-- 每周活跃度进度条 -->
        <div class="progress-bar-container">
          <div class="progress-bar">
            <div class="progress-fill weekly" :style="{ width: weeklyProgressWidth + '%' }"></div>
          </div>
          
          <!-- 每周宝箱 -->
          <div class="box-container">
            <div 
              v-for="(box, index) in taskInfo.week_score_task || []" 
              :key="'weekly-' + index"
              class="activity-box"
              :class="{ 
                'can-claim': box.status === 1, 
                'claimed': box.status === 2,
                'locked': box.status === 0
              }"
              @click="claimBox(2, box)"
              @mouseenter="showRewardTooltip($event, box, 'weekly')"
              @mouseleave="hideRewardTooltip"
            >
              <div class="box-icon">{{ box.need_score }}</div>
              <div class="box-label">{{ box.status === 2 ? '已领取' : (box.status === 1 ? '可领取' : '未达成') }}</div>
            </div>
          </div>
        </div>
      </div>
      
      <!-- 每日任务列表 -->
      <div class="task-list-container scroll-panel">
        <div class="task-list-header">
          <div class="task-title">每日任务</div>
          <div class="refresh-btn btn-sword" @click="refreshTasks">刷新</div>
        </div>
        
        <div class="task-list">
          <div 
            v-for="(task, index) in sortedDailyTasks" 
            :key="index"
            class="task-item"
            :class="{ 'completed': isTaskCompleted(task) }"
          >
            <div class="task-content">
              <div class="task-name">{{ task.desc }}</div>
              <div class="task-progress">完成度:{{ task.finish[0] }}/{{ task.finish[1] }}</div>
            </div>
            <div class="task-reward">
              <span class="activity-value">活跃度+{{ task.reward_score }}</span>
              <span class="task-status">{{ isTaskCompleted(task) ? '已完成' : '进行中' }}</span>
            </div>
          </div>
        </div>
      </div>
      
      <!-- 底部提示 -->
      <div class="bottom-tip">
        每日0点刷新日常任务，每周一0点刷新周活跃
      </div>
    </div>
    

    

    

    

    

    
    <!-- 奖励提示框 -->
    <div 
      v-if="rewardTooltip.visible" 
      class="reward-tooltip"
      :style="{ left: rewardTooltip.x + 'px', top: rewardTooltip.y + 'px' }"
    >
      <div class="tooltip-header">
        <span class="tooltip-title">{{ rewardTooltip.type === 'daily' ? '每日' : '每周' }}宝箱奖励</span>
        <span class="tooltip-score">{{ rewardTooltip.score }}分</span>
      </div>
      <div class="tooltip-content">
        <div class="reward-item">
          <span class="reward-icon">🎁</span>
          <span class="reward-text">{{ rewardTooltip.description }}</span>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { getTaskInfo, claimTaskReward } from '@/api/activity'

export default {
  data() {
    return {
      // 当前选中的标签页
      currentTab: 'daily',
      
      // 活动标签页配置
      activityTabs: [
        { id: 'daily', name: '每日活跃', icon: '📋', hasBadge: false },
        { id: 'login', name: '连续登录', icon: '📆', hasBadge: false },
        { id: 'achievement', name: '成就系统', icon: '🏆', hasBadge: true },
        { id: 'level', name: '等级奖励', icon: '📈', hasBadge: false },
        { id: 'monthly', name: '月签到', icon: '📅', hasBadge: false },
        { id: 'newbie', name: '新人七日', icon: '🎁', hasBadge: false }
      ],
      
      // 任务信息数据
      taskInfo: {
        day_task_list: [],
        day_score: 0,
        day_score_task: [],
        week_score: 0,
        week_score_task: []
      },
      
      // 最大分数配置
      dailyMaxActivity: 150,
      weeklyMaxActivity: 1000,
      
      // 奖励提示框
      rewardTooltip: {
        visible: false,
        x: 0,
        y: 0,
        type: '',
        score: 0,
        description: ''
      },
      
      // 奖励配置数据
      rewardConfig: {
        daily: {
          30: "随机突破丹药5个",
          60: "200先天灵石", 
          90: "随机法宝3阶以上法宝",
          120: "20功德",
          150: "随机3阶以上请神令1个"
        },
        weekly: {
          150: "随机功法3本",
          300: "2000先天灵石",
          450: "随机灵根4个", 
          600: "100功德",
          900: "随机阵法2本"
        }
      },

    }
  },
  
  computed: {
    // 计算每日活跃度进度条宽度
    dailyProgressWidth() {
      const score = this.taskInfo.day_score || 0
      return Math.min(100, (score / this.dailyMaxActivity) * 100)
    },
    
    // 计算每周活跃度进度条宽度
    weeklyProgressWidth() {
      const score = this.taskInfo.week_score || 0
      return Math.min(100, (score / this.weeklyMaxActivity) * 100)
    },
    
    // 排序后的每日任务列表（未完成在上方，已完成置灰在下方）
    sortedDailyTasks() {
      const tasks = this.taskInfo.day_task_list || []
      return [...tasks].sort((a, b) => {
        const aCompleted = this.isTaskCompleted(a)
        const bCompleted = this.isTaskCompleted(b)
        
        // 未完成的任务排在前面
        if (aCompleted && !bCompleted) return 1
        if (!aCompleted && bCompleted) return -1
        return 0
      })
    },
    

    
    // 当前月份和年份显示
    currentMonthYear() {
      const date = new Date()
      const year = date.getFullYear()
      const month = date.getMonth() + 1
      return `${year}年${month}月`
    }
  },
  
  created() {
    // 先填充mock数据，确保布局完整展示
    this.applyMockData()
    // 再请求真实数据覆盖
    this.fetchActivityData()
  },
  
  methods: {
    // 切换标签页
    switchTab(tabId) {
      this.currentTab = tabId
    },
    
    // 返回上一页
    goBack() {
      uni.navigateBack()
    },

    // 子页面导航
    goToSubPage(tabId) {
      const map = {
        achievement: '/pages/activity/achievement',
        level: '/pages/activity/level',
        monthly: '/pages/activity/monthly',
        login: '/pages/activity/login',
        newbie: '/pages/activity/newbie'
      }
      const url = map[tabId]
      if (!url) {
        uni.showToast({ title: '该功能已拆分，稍后开放', icon: 'none' })
        return
      }
      uni.navigateTo({ url })
    },

    // 判断任务是否完成
    isTaskCompleted(task) {
      return task.finish && task.finish[0] >= task.finish[1]
    },
    
    // 获取活跃度数据
    async fetchActivityData() {
      try {
        const result = await getTaskInfo()
        if (result.code === 1) {
          this.taskInfo = result.data || {}
        } else {
          uni.showToast({
            title: result.message || '获取数据失败',
            icon: 'none'
          })
        }
      } catch (error) {
        console.error('获取活跃度数据失败:', error)
        uni.showToast({
          title: '获取数据失败，请稍后再试',
          icon: 'none'
        })
      }
    },
    
    // 领取宝箱
    async claimBox(taskType, box) {
      // 检查是否可以领取
      if (box.status !== 1) {
        if (box.status === 0) {
          uni.showToast({
            title: '未达到领取条件',
            icon: 'none'
          })
        } else if (box.status === 2) {
          uni.showToast({
            title: '已经领取过了',
            icon: 'none'
          })
        }
        return
      }
      
      try {
        const result = await claimTaskReward({
          task_type: taskType,
          need_score: box.need_score
        })
        
        if (result.code === 1) {
          // 更新状态
          box.status = 2
          
          uni.showToast({
            title: '领取成功',
            icon: 'success'
          })
          
          // 刷新数据
          this.fetchActivityData()
        } else {
          uni.showToast({
            title: result.message || '领取失败',
            icon: 'none'
          })
        }
      } catch (error) {
        console.error('领取宝箱失败:', error)
        uni.showToast({
          title: '领取失败，请稍后再试',
          icon: 'none'
        })
      }
    },
    
    // 刷新任务
    refreshTasks() {
      this.fetchActivityData()
      uni.showToast({
        title: '刷新成功',
        icon: 'success'
      })
    },
    
    // 显示奖励提示框
    showRewardTooltip(event, box, type) {
      const description = type === 'daily' 
        ? this.rewardConfig.daily[box.need_score]
        : this.rewardConfig.weekly[box.need_score]
      
      this.rewardTooltip = {
        visible: true,
        x: event.clientX,
        y: event.clientY,
        type,
        score: box.need_score,
        description: description || '未知奖励'
      }
    },
    
    // 隐藏奖励提示框
    hideRewardTooltip() {
      this.rewardTooltip.visible = false
    },
    
    // 其他子模块逻辑已迁移至各自子页面

    // 预填充mock数据，确保布局完整展示
    applyMockData() {
      this.taskInfo = {
        day_task_list: [
          { desc: '完成一次挑战', finish: [0, 1], reward_score: 30 },
          { desc: '挂机领取奖励', finish: [1, 1], reward_score: 20 },
          { desc: '进行一次修炼', finish: [2, 3], reward_score: 25 },
          { desc: '完成日常对话', finish: [0, 2], reward_score: 20 },
          { desc: '收集素材', finish: [5, 10], reward_score: 15 },
        ],
        day_score: 85,
        day_score_task: [
          { need_score: 30, status: 2 },
          { need_score: 60, status: 1 },
          { need_score: 90, status: 0 },
          { need_score: 120, status: 0 },
          { need_score: 150, status: 0 },
        ],
        week_score: 320,
        week_score_task: [
          { need_score: 150, status: 2 },
          { need_score: 300, status: 1 },
          { need_score: 450, status: 0 },
          { need_score: 600, status: 0 },
          { need_score: 900, status: 0 },
        ],
      }
    }
  }
}
</script>

<style scoped>
@import url('https://fonts.googleapis.com/css2?family=Ma+Shan+Zheng&display=swap');

.activity-container {
  min-height: 100vh;
  background-color: #f8f6f1; /* 米白底 */
  background-image: radial-gradient(circle at 20% 15%, rgba(0,0,0,0.04) 0, rgba(0,0,0,0.0) 60%),
                    radial-gradient(circle at 80% 85%, rgba(0,0,0,0.04) 0, rgba(0,0,0,0.0) 60%);
  padding-bottom: 30rpx;
}

/* 顶部导航栏 */
.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 30rpx 40rpx;
  background: transparent;
  color: #4b3a2a; /* 深褐 */
  border-bottom: 1rpx solid #d8c7a3;
}

.back-btn {
  font-size: 28rpx;
}

.brush-title {
  font-family: 'Ma Shan Zheng', 'Kaiti SC', 'STKaiti', serif;
  font-size: 40rpx;
  color: #4b3a2a;
  letter-spacing: 2rpx;
}

.placeholder {
  width: 80rpx;
}

/* 活动导航样式 */
.activity-nav {
  display: flex;
  justify-content: space-around;
  background-color: #fbf9f3;
  padding: 20rpx 0;
  margin-bottom: 30rpx;
  border-bottom: 1rpx solid #e2d6bd;
  overflow-x: auto;
}

.nav-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 16rpx 30rpx;
  cursor: pointer;
  position: relative;
  min-width: 120rpx;
}

.nav-item.active {
  background-color: #8c6b52;
  border-radius: 16rpx;
  color: #fff;
}

.nav-icon {
  font-size: 36rpx;
  margin-bottom: 10rpx;
}

.nav-label {
  font-size: 24rpx;
}

.nav-badge {
  position: absolute;
  top: 0;
  right: 0;
  background-color: #c89a5b;
  color: white;
  border-radius: 50%;
  width: 32rpx;
  height: 32rpx;
  font-size: 20rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

/* 活跃度进度条 */
.activity-progress {
  background-color: #fbf9f3; /* 淡米白面板 */
  margin: 30rpx;
  padding: 36rpx; /* 增加内边距，避免边框过紧 */
  border-radius: 16rpx;
  border: 1rpx solid #e2d6bd;
  box-shadow: 0 4rpx 16rpx rgba(75, 58, 42, 0.06);
}

.progress-title {
  display: flex;
  justify-content: space-between;
  margin-bottom: 24rpx; /* 增加底部间距 */
  font-size: 28rpx;
  color: #4b3a2a;
}

.progress-bar-container {
  margin-bottom: 44rpx; /* 增强区块分隔感 */
}

.progress-bar {
  height: 20rpx;
  background-color: #e6e0d6; /* 浅灰米色 */
  border-radius: 10rpx;
  margin-bottom: 20rpx;
  position: relative;
}

.progress-fill {
  height: 100%;
  background: linear-gradient(90deg, #8c6b52 0%, #6b4f3b 100%); /* 深褐渐变 */
  border-radius: 10rpx;
  transition: width 0.3s ease;
}

.progress-fill.weekly {
  background: linear-gradient(90deg, #5a3f2f 0%, #3e2c22 100%);
}

/* 宝箱样式 */
.box-container {
  display: flex;
  justify-content: space-between;
  margin-top: 24rpx; /* 增加顶部间距 */
}

.activity-box {
  display: flex;
  flex-direction: column;
  align-items: center;
  cursor: pointer;
}

.box-icon {
  width: 64rpx;
  height: 64rpx;
  background-color: #fbf9f3;
  border: 1rpx solid #d8c7a3;
  border-radius: 8rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24rpx;
  color: #6b4f3b;
  margin-bottom: 8rpx;
}

.box-label {
  font-size: 22rpx;
  color: #7a6a5c;
}

/* 宝箱状态 */
.activity-box.can-claim .box-icon {
  background: linear-gradient(135deg, #e6c089 0%, #c89a5b 100%);
  color: #fff;
}

.activity-box.claimed .box-icon {
  background-color: #ece6dc;
  color: #9c8f83;
}

.activity-box.locked .box-icon {
  background-color: #f3efe7;
  color: #b0a79f;
}

/* 任务列表卷轴面板 */
.scroll-panel {
  background-color: #fbf9f3;
  margin: 30rpx;
  padding: 34rpx 34rpx 44rpx; /* 增加内边距 */
  border-radius: 12rpx;
  border: 1rpx solid #d8c7a3;
  box-shadow: 0 6rpx 20rpx rgba(75, 58, 42, 0.08);
  position: relative;
}
.scroll-panel::before, .scroll-panel::after {
  content: "";
  position: absolute;
  left: 16rpx;
  right: 16rpx;
  height: 16rpx;
  background: radial-gradient(circle at left, rgba(216,199,163,0.6), transparent 70%),
              radial-gradient(circle at right, rgba(216,199,163,0.6), transparent 70%);
}
.scroll-panel::before { top: -10rpx; }
.scroll-panel::after { bottom: -10rpx; }

.task-list-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24rpx;
}

.task-title {
  font-size: 32rpx;
  font-weight: 600;
  color: #4b3a2a;
}

/* 剑形按钮 */
.btn-sword {
  position: relative;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  padding: 10rpx 32rpx 10rpx 28rpx;
  background: #6b4f3b;
  color: #fff;
  border-radius: 8rpx;
  border: 1rpx solid #4b3a2a;
  overflow: visible;
}
.btn-sword::before {
  content: "";
  position: absolute;
  right: -14rpx;
  top: 50%;
  transform: translateY(-50%);
  width: 0; height: 0;
  border-top: 10rpx solid transparent;
  border-bottom: 10rpx solid transparent;
  border-left: 14rpx solid #6b4f3b; /* 剑尖 */
}
.btn-sword::after {
  content: "";
  position: absolute;
  left: -10rpx;
  top: 50%;
  transform: translateY(-50%);
  width: 6rpx; height: 26rpx;
  background: #4b3a2a; /* 剑柄 */
  border-radius: 2rpx;
}
.btn-sword:hover { filter: brightness(1.05); }

.refresh-btn {
  font-size: 26rpx;
}

/* 任务列表 */
.task-list {
  margin-top: 10rpx;
}

.task-item {
  display: flex;
  justify-content: space-between;
  padding: 28rpx 12rpx; /* 增加内边距，左右留白更舒适 */
  border-bottom: 1rpx dashed #e2d6bd;
  transition: all 0.3s ease;
}

.task-item:last-child {
  border-bottom: none;
}

.task-name {
  font-size: 28rpx;
  color: #3e2c22;
  margin-bottom: 8rpx;
}

.task-progress {
  font-size: 24rpx;
  color: #7a6a5c;
}

.task-reward {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
}

.activity-value {
  font-size: 26rpx;
  color: #8c6b52;
  margin-bottom: 8rpx;
}

.task-status {
  font-size: 24rpx;
  color: #7a6a5c;
}

/* 已完成任务样式 */
.task-item.completed {
  opacity: 0.7;
}

.task-item.completed .task-name,
.task-item.completed .task-progress {
  color: #9c8f83;
}

.task-item.completed .activity-value {
  color: #b7a89a;
}

.task-item.completed .task-status {
  color: #6b4f3b;
}

/* 底部提示 */
.bottom-tip {
  text-align: center;
  font-size: 24rpx;
  color: #7a6a5c;
  margin: 30rpx 0;
}

/* 奖励提示框 */
.reward-tooltip {
  position: fixed;
  z-index: 9999;
  background: #2c1810;
  color: #f8f6f1;
  border-radius: 12rpx;
  padding: 16rpx 20rpx;
  box-shadow: 0 8rpx 24rpx rgba(44, 24, 16, 0.4);
  border: 1rpx solid #6b4f3b;
  min-width: 200rpx;
  max-width: 300rpx;
  pointer-events: none;
}

.tooltip-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12rpx;
  padding-bottom: 8rpx;
  border-bottom: 1rpx solid #4b3a2a;
}

.tooltip-title {
  font-size: 26rpx;
  font-weight: 600;
  color: #e6c089;
}

.tooltip-score {
  font-size: 24rpx;
  color: #c89a5b;
  background: rgba(230, 192, 137, 0.2);
  padding: 4rpx 8rpx;
  border-radius: 6rpx;
}

.tooltip-content {
  font-size: 24rpx;
  line-height: 1.4;
}

.reward-item {
  display: flex;
  align-items: center;
  gap: 8rpx;
}

.reward-icon {
  font-size: 28rpx;
  filter: sepia(1) hue-rotate(30deg) brightness(1.2);
}

.reward-text {
  color: #f0e6d6;
  flex: 1;
}
/* 对比度与武侠风格增强 */
.panel-container {
  display: flex;
  flex-direction: column;
  gap: 20rpx;
  padding-bottom: 20rpx;
}
.activity-container {
  background-color: #f5f1ea; /* 更柔和浅底，提高文字对比 */
}
.activity-progress, .scroll-panel {
  background-color: #ffffff; /* 白色卡片容器 */
  border-color: #d8c7a3;
}
.brush-title { color: #2e1a0f; }
.nav-item.active { background-color: #5b3a1d; }
.progress-bar { background-color: #d9d2c7; }
.task-name { color: #2e1a0f; }
.task-progress, .task-status { color: #4b3a2a; }
/* 内容占满空间：避免过多外边距在小屏留下空白 */
.task-list { margin-top: 0; }
</style>